package testJdk.net.testTcp2;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.nio.charset.StandardCharsets;

/**
 * @author keyer
 * @Name : learn_jdk.net.testTcp2.Server
 * @Description : 描述
 * Created by cyd on 2021-07-15 15:46:32
 */
public class Server {
    public static void main(String[] args) throws Exception {
        // 通过这个就可以得到主机的IP，这个ip是我们的服务器端：192.168.228.1
        //DESKTOP-77SLD3H/DESKTOP-77SLD3H/192.168.228.1
        System.out.println(InetAddress.getLocalHost());

        // 创建服务
        ServerSocket serverSocket = new ServerSocket(10003);
        // 监听客户端连接
        // 阻塞式监听，会一直监听客户端的连接
        Socket socket = serverSocket.accept();
        // 获取输入流
        InputStream inputStream = socket.getInputStream();

        // 管道流
//        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        OutputStream out = socket.getOutputStream();
        int len = 0;
        byte[] buffer = new byte[1024];
        while ((len = inputStream.read(buffer)) != -1) {

            System.out.println(new String(buffer, 0, len));
            String s = "echo:" + new String(buffer, 0, len);
            byte[] bytes = s.getBytes(StandardCharsets.UTF_8);
            out.write(bytes);
        }

        // 关闭资源
//        byteArrayOutputStream.close();
        socket.close();
        serverSocket.close();
    }

}
